package cn.cvs.test;

import cn.cvs.dao.SupplierMapper;
import cn.cvs.dao.SysUserMapper;
import cn.cvs.dao.Commodity;
import cn.cvs.pojo.Address;
import cn.cvs.pojo.StorageRecord;
import cn.cvs.pojo.Supplier;
import cn.cvs.pojo.SysUser;
import cn.cvs.util.MyBatisUtil;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MybatisTest extends MyBatisUtil {
    private  static final Logger logger = Logger.getLogger(MybatisTest.class.getName());
    @Test
    public void testCount() throws IOException {

        // 读取mybatis核心配置文件
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");

        // 创建 SqlSessionFactoryBuilder  构建者 对象
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();

        // 创建 SqlSessionFactory 对象
        SqlSessionFactory factory = builder.build(is);

        // 创建 SqlSession 对象
        SqlSession sqlSession = factory.openSession();

        //获取 SysUserMapper 对象
        SysUserMapper mapper = sqlSession.getMapper(SysUserMapper.class);

       // SysUserMapper sysUserMapper = new SysUserMapperImpl();

        // 调用 方法 ，执行SQL
        int count = mapper.count();

        System.out.println(count);

        // 关闭session
        closeSqlSession(sqlSession);
    }
    @Test
    public void testSupplier(){
        SqlSession  sqlSession;
        List<Supplier> supList;

        sqlSession =createSqlSession();

        SupplierMapper mapper = sqlSession.getMapper(SupplierMapper.class);
        supList = mapper.supplierSup();
        for (Supplier supplier:supList) {
            String str = String.format("主键ID:%s   供货商编号:%s  供货商名称:%s  供货商描述:%s  供货商联系人%s  联系电话%s  供货商地址%s  传真创建人id%s  创建时间%s  修改时间%s  修改人id%s  "
            ,supplier.getId(),supplier.getSupCode(),supplier.getSupName(),supplier.getSupDesc(),supplier.getSupContact(),supplier.getSupPhone(),supplier.getSupAddress(),supplier.getSupFax(),supplier.getCreatedUserId(),supplier.getCreatedTime(),supplier.getUpdatedTime(),supplier.getUpdatedUserId());
            System.out.println(str);
        }
        closeSqlSession(sqlSession);
    }
    @Test
    public void testList() {


        SqlSession sqlSession = createSqlSession();

        SysUserMapper mapper = sqlSession.getMapper(SysUserMapper.class);

        List<SysUser> list = mapper.getUserList();

        for (SysUser sysUser : list) {
            String s = String.format("ID:%s，RealName:%s", sysUser.getId(), sysUser.getRealName());

            System.out.println(s);
        }

        closeSqlSession(sqlSession);
    }
    @Test
    public void testSysUser() {

        SqlSession sqlSession = createSqlSession();

        SysUserMapper mapper = sqlSession.getMapper(SysUserMapper.class);

        SysUser sysUser = mapper.getUser(2);

        System.out.println("id="+sysUser.getId()+"name="+sysUser.getRealName());

        closeSqlSession(sqlSession);

    }
    @Test
    public void  testSysUserList(){
        SqlSession  sqlSession;
        List<SysUser> userList;
            sqlSession = createSqlSession();
            SysUser sysUser = new SysUser();
            sysUser.setRealName("李");
//           sysUser.setRoleId(3);
//           userList = sqlSession.getMapper(SysUserMapper.class).getUserByRealName("李"); //示例1
//            userList = sqlSession.getMapper(SysUserMapper.class).getUserListByPojo(sysUser);  //示例3
//            Map<String,Object> userMap = new HashMap<String,Object>();
//            userMap.put("rName","赵");
//            userMap.put("rId",2);
//            userList  =sqlSession.getMapper(SysUserMapper.class).getUserListByMap(userMap);//示例七
//            userList = sqlSession.getMapper(SysUserMapper.class).getUserListByParams("赵",2);//示例十

//            userList = sqlSession.getMapper(SysUserMapper.class).getUserListWithRoleName(sysUser);//示例十三
            userList =sqlSession.getMapper(SysUserMapper.class). getUserListByRoleId(3);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-hh");
            for (SysUser user :userList) {
//                String str = String.format("姓名:  %s  性别:  %s  联系电话:  %s  现居地址:  %s  出生日期:  %s  角色:  %s ",user.getRealName(),user.getSex()==2?"男":"女",user.getPhone(),user.getAddress(),format.format(user.getBirthday()),user.getUserRoleName());
//             String str  = String.format("编码%s   ",user.getUserCode());
//                System.out.println(str);
                logger.info("用户名   " + user.getRealName() + "    用户编码  " + user.getSysRole().getCode() + "   角色名称   " + user.getSysRole().getRoleName());//示例17


            }
        closeSqlSession(sqlSession);
    }
    @Test
    public void testSysUserAddress(){
        SqlSession sqlSession = createSqlSession();
        List<SysUser> userList = sqlSession.getMapper(SysUserMapper.class).getUserAndAddressByUserId(1);
        for (SysUser sysUser:userList) {
            logger.info("userList(include:addressList)===>account:" +
                    sysUser.getAddress()+",realName:"+sysUser.getRealName());
            for (Address address : sysUser.getAddressList()) {
                logger.info("address ----> id:"+address.getId()
                +",contact: "+address.getContact()
                +",addressDesc: "+address.getAddressDesc()
                +",tel: "+address.getTel()
                +",postCode: "+address.getPostCode()
                );
            }
        }
    }
    @Test
    public void testAdd(){
        logger.info("testAdd !=========================");
        SqlSession sqlSession = null;
        int count;
        try {
            sqlSession = createSqlSession();
            SysUser user = new SysUser();
            user.setAccount("test001");
            user.setRealName("测试用户001");
            user.setPassword("1234567");
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            user.setBirthday(format.parse("2003-10-22"));
            user.setAddress("测试地址abc");
            user.setSex(1);
            user.setPhone("13411110000");
            user.setRoleId(1);
            user.setCreatedUserId(1);
            user.setCreatedTime(new Date());
            count = sqlSession.getMapper(SysUserMapper.class).add(user);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
            assert sqlSession != null;
            sqlSession.rollback();
            count = 0;
        }finally {
            closeSqlSession(sqlSession);
        }
        logger.info("testAdd count:"+count);
    }
    @Test
    public void testUpdate(){
        logger.info("testAdd !=========================");
        SqlSession sqlSession = null;
        int count;
        try {
            sqlSession = createSqlSession();
            SysUser user = new SysUser();
            user.setId(18);
            user.setAccount("test002");
            user.setRealName("测试用户001");
            user.setPassword("1111111");
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            user.setBirthday(format.parse("2003-10-22"));
            user.setAddress("测试地址abc");
            user.setSex(1);
            user.setPhone("13411110000");
            user.setRoleId(1);
            user.setCreatedUserId(1);
            user.setCreatedTime(new Date());
            count = sqlSession.getMapper(SysUserMapper.class).modify(user);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
            assert sqlSession != null;
            sqlSession.rollback();
            count = 0;
        }finally {
            closeSqlSession(sqlSession);
        }
        logger.info("modify count:"+count);
    }
    @Test
    public void testUpdatePassword(){
        logger.info("testUpdatePassword==========================");
        SqlSession sqlSession = null;
        String pwd = "888888888";
        Integer id = 18;
        int count;
        try {
            sqlSession = createSqlSession();
            count = sqlSession.getMapper(SysUserMapper.class)  .updatePwd(id,pwd);
            sqlSession.commit();
        }catch (Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            count = 0;
        }finally {
            closeSqlSession(sqlSession);
        }
        logger.info("testUpdatePwd count:"+count);

    }
    @Test
    public void testDeleteUserById(){
        logger.info("testDeleteUserById====================================");
        SqlSession sqlSession=  null;
        Integer id=18;
        int count =0;
        try {
            sqlSession  = createSqlSession();
            count= sqlSession.getMapper(SysUserMapper.class).deleteUserById(id);
            sqlSession.commit();
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            count = 0;
            logger.error(e);
        }finally {
            closeSqlSession(sqlSession);
        }
        logger.info("deleteUserById count:"+count);
    }

    //第二章上机1
    @Test
    public void  testcommodity(){
        SqlSession  sqlSession;
        List<StorageRecord> storageRecordList;
        sqlSession = createSqlSession();
        StorageRecord storageRecord = new StorageRecord();
        storageRecord.setGoodsName("习");
        storageRecord.setSupplierId(1);
        storageRecord.setPayStatus(1);
        storageRecordList = sqlSession.getMapper(Commodity.class).selectCommodity(storageRecord);
        for (StorageRecord storage : storageRecordList) {
            logger.info("入库记录编码:" + storage.getSrCode() + "商品名称:" + storage.getGoodsName() + "供货商ID:" + storage.getSupplierId() + "支付状态:" + storage.getPayStatus() + "创建时间:" + storage.getCreatedTime());//示例17
        }
        closeSqlSession(sqlSession);
    }

    //第二章上机2
    @Test
    public void testStorageRecordByMap(){
        SqlSession  sqlSession;
        Map<String,Object> storageRecordMap = new HashMap<String,Object>();
        sqlSession = createSqlSession();
        storageRecordMap.put("goodsName","百");
        storageRecordMap.put("supplierId",2);
        storageRecordMap.put("payStatus",2);
        List<StorageRecord> storageRecordList = sqlSession.getMapper(Commodity.class).getStorageRecordByMap(storageRecordMap);
        for (StorageRecord storage : storageRecordList) {
            logger.info("入库记录编码:" + storage.getSrCode() + "商品名称:" + storage.getGoodsName() + "供货商ID:" + storage.getSupplierId() + "支付状态:" + storage.getPayStatus() + "创建时间:" + storage.getCreatedTime());
        }
        closeSqlSession(sqlSession);
    }

    //第二章上机3
    @Test
    public void testAssociation(){
        SqlSession  sqlSession;
        List<StorageRecord> storageRecordList;
        sqlSession = createSqlSession();
        StorageRecord storageRecord = new StorageRecord();
        storageRecord.setGoodsName("习");
        storageRecord.setSupplierId(1);
        storageRecord.setPayStatus(1);
        storageRecordList = sqlSession.getMapper(Commodity.class).selectStorageRecordByMap(storageRecord);


        for (StorageRecord storage : storageRecordList) {
            logger.info("入库记录编码:" + storage.getSrCode() + "\n商品名称:" + storage.getGoodsName() + "\n供货商编码:" + storage.getSupplier().getSupCode() + "\n供货商名称:" + storage.getSupplier().getSupName() + "\n联系人:" + storage.getSupplier().getSupContact() + "\n联系电话:" + storage.getSupplier().getSupPhone() + "\n商品总额:" + storage.getTotalAmount() + "\n支付状态:" + storage.getPayStatus());
        }
        sqlSession.close();
    }

    //第二章上机4
    @Test
    public void testSelectAllStorageRecord(){
        SqlSession  sqlSession;
        sqlSession = createSqlSession();
        List<Supplier> supplierList = sqlSession.getMapper(Commodity.class).selectAllStorageRecord(1);

        for (Supplier supplier : supplierList) {
            logger.info("供货商ID:" + supplier.getId() + "\n供货商编码:" + supplier.getSupCode() + "\n供货商名称:" + supplier.getSupName() + "\n联系人:" + supplier.getSupContact() + "\n联系电话:" + supplier.getSupPhone());
            for (StorageRecord storageRecord : supplier.getStorageRecordList()){
                logger.debug("入库记录编码:" + storageRecord.getSrCode() + "\n商品名称:" + storageRecord.getGoodsName() + "\n商品总额:" + storageRecord.getTotalAmount() + "\n支付状态:" + storageRecord.getPayStatus());
            }
        }
        sqlSession.close();
    }

    //第二章上机5(新增)
    @Test
    public void testadd(){
        logger.info("testAdd !=========================");
        SqlSession sqlSession = null;
        int count;
        try {
            sqlSession = createSqlSession();
            Supplier supplier = new Supplier();
            supplier.setSupCode("CZ_GYS001");
            supplier.setSupName("郴州zero-x科技有限公司");
            supplier.setSupDesc("主营产品:软件应用");
            supplier.setSupContact("刘志辉");
            supplier.setSupPhone("13678912123");
            supplier.setSupAddress("郴州北大青鸟");
            supplier.setSupFax("010-13678912123");
            supplier.setCreatedUserId(1);
            supplier.setCreatedTime(new Date());
            supplier.setUpdatedTime(null);
            supplier.setUpdatedUserId(null);
            count = sqlSession.getMapper(Commodity.class).add(supplier);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
            assert sqlSession != null;
            sqlSession.rollback();
            count = 0;
        }finally {
            closeSqlSession(sqlSession);
        }
        logger.info("testAdd count:"+count);
    }

    //第二章上机5(修改)
    @Test
    public void testupdate(){
        logger.info("testUpdata !=========================");
        SqlSession sqlSession = null;
        int count;
        try {
            sqlSession = createSqlSession();
            Supplier supplier = new Supplier();
            supplier.setId(16);
            supplier.setSupCode("CZ_GYS001");
            supplier.setSupName("郴州zero-x科技有限公司");
            supplier.setSupDesc("主营产品:软件应用");
            supplier.setSupContact("刘某辉");
            supplier.setSupPhone("13678912123");
            supplier.setSupAddress("郴州北大青鸟");
            supplier.setSupFax("010-13678912123");
            supplier.setCreatedUserId(1);
            supplier.setCreatedTime(new Date());
            supplier.setUpdatedTime(null);
            supplier.setUpdatedUserId(null);
            count = sqlSession.getMapper(Commodity.class).modify(supplier);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
            assert sqlSession != null;
            sqlSession.rollback();
            count = 0;
        }finally {
            closeSqlSession(sqlSession);
        }
        logger.info("modify count:"+count);
    }

    //第二章上机5(删除)
    @Test
    public void testdelete(){
        logger.info("testdelete !=========================");
        SqlSession sqlSession = null;
        int count;
        try {
            sqlSession = createSqlSession();
            Supplier supplier = new Supplier();
            supplier.setId(16);
            count = sqlSession.getMapper(Commodity.class).modify(supplier);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
            assert sqlSession != null;
            sqlSession.rollback();
            count = 0;
        }finally {
            closeSqlSession(sqlSession);
        }
        logger.info("modify count:"+count);
    }
}
